package com.jingxuan.controller;

import com.jingxuan.common.annotation.NoAuth;
import com.jingxuan.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查控制器
 */
@RestController
@RequestMapping("/actuator")
public class HealthCheckController {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 健康检查接口
     * GET /api/actuator/health
     */
    @NoAuth
    @GetMapping("/health")
    public Result<Map<String, Object>> health() {
        Map<String, Object> healthInfo = new HashMap<>();
        
        try {
            // 检查数据库连接
            try (Connection connection = dataSource.getConnection()) {
                healthInfo.put("database", "UP");
            } catch (Exception e) {
                healthInfo.put("database", "DOWN: " + e.getMessage());
            }
            
            // 检查Redis连接
            try {
                redisTemplate.opsForValue().get("health_check");
                healthInfo.put("redis", "UP");
            } catch (Exception e) {
                healthInfo.put("redis", "DOWN: " + e.getMessage());
            }
            
            // 应用状态
            healthInfo.put("application", "UP");
            healthInfo.put("timestamp", LocalDateTime.now());
            healthInfo.put("status", "UP");
            
            return Result.success("服务健康", healthInfo);
        } catch (Exception e) {
            healthInfo.put("status", "DOWN");
            healthInfo.put("error", e.getMessage());
            return Result.error(5000, "服务异常: " + e.getMessage());
        }
    }

    /**
     * 简单的ping接口
     * GET /api/actuator/ping
     */
    @NoAuth
    @GetMapping("/ping")
    public Result<String> ping() {
        return Result.success("pong", "服务正常运行");
    }
}